package bean;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;




import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;


public class portDTO {
	public 	ArrayList<PortfolioVo> al;
	private PortfolioVo vo;
	Connection conn = null;
//	private Connection conn =null;
	
	// 페이지와 관련된 변수들
		int blockSize = 5; //한블럭당 표시되는 페이지 수
		int listSize = 20;  //페이지당 표시되는 행수
		int totSize = 0;   //전체 게시물의 갯수
		int totPage = 0;   //전체 페이지 수
		int totBlock = 0;  //전체 블럭 수
		int nowPage = 0;   //현재 페이지
		int nowBlock = 0;  //현재 블럭
		int startNo = 0;   //리스트 목록의 시작 위치
		int endNo = 0;     //리스트 목록의 끝 위치
		int startPage = 0; //현재 블럭에서 표시되는 시작 블럭 번호
		int endPage = 0;   //현재 블럭에서 표시되는 끝 블럭 번호
	
//		String saveDir="D:/jsy/kiSunnyShop/WebContent/memberPhoto";
		String saveDir="F:/자바/학원/and_1406/2/kiSunnyShop/WebContent/memberPhoto";
	public portDTO() 
	{
		conn = new MyOracle().getConn();
	}
	
//	public portDTO(){	
//		try{
//			Context init = new InitialContext();
//			DataSource ds = (DataSource)init.lookup("java:comp/env/jdbc/OracleDB");
//			conn = ds.getConnection();
//			System.out.println("<h3>연결에 성공하였습니다</h3>");
//
//		}catch(Exception e){
//			System.out.println("<h3>연결에 실패하였습니다</h3>");
//			e.printStackTrace();
//		}
//	}
	
	public PortfolioVo selectOne1()
	{
		PortfolioVo v = new PortfolioVo();
		String sql = "select * from portfolio where rno=?";
		try
		{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, vo.getRno());
			ResultSet rs = pst.executeQuery();
			if(rs.next())
			{
				v.setRno(rs.getInt("rno"));
				v.setPrno(rs.getInt("prno"));
				v.setCate(rs.getString("cate"));
				v.setSubject(rs.getString("subject"));
				v.setContent(rs.getString("content"));
				v.setPhoto(rs.getString("photo"));
				v.setWdate(rs.getString("wdate"));
				v.setWriter(rs.getString("writer"));
				v.setPwd(rs.getString("pwd"));
				v.setReview(rs.getInt("review"));
				v.setThumb(rs.getString("thumb"));
				
			}
			
			pst.close();
//			conn.close();
		}
		
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		return v;		
	}

	public boolean review()
	{
		boolean b=false;
		
		String sql="update portfolio set review = nvl(review,0)+1 where rno = ?";
		try
		{			
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, vo.getRno());
			System.out.println("rno "+vo.getRno());
			int cnt = pst.executeUpdate();
			b=true;
			pst.close();
			conn.close();
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		return b;		
	}
	
	
	public boolean delete()
	{
		boolean b=false;
		
		String sql="delete from portfolio where rno=? ";
		
		try
		{			
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1,vo.getRno2());
			System.out.println("rno2 "+vo.getRno2());
			int cnt = pst.executeUpdate();
			b=true;
			String saveDir="F:/자바/학원/and_1406/2/kiSunnyShop/WebContent/memberPhoto";
//			String saveDir="C:/Users/jhta/javaWorkspace/Test/WebContent/memberPhoto";
			
			File f = new File(saveDir+vo.getPhoto());
			pst.close();
			conn.close();
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		return b;		
	}
	
	public void input()
	{
		try
		{			
			String sql="insert into portfolio(prno, cate,subject,content,photo,wdate,writer,pwd,rno,review) "
					+ "values(?,?,?,?,?,sysdate,?,?,seq_portfolio_rno.nextval,0)";
			PreparedStatement pst = conn.prepareStatement(sql);
//			pst.setString(1, "seq_portfolio_rno.nextval");
			pst.setInt(1, vo.getPrno());
			pst.setString(2, vo.getCate());
			pst.setString(3, vo.getSubject());
			pst.setString(4, vo.getContent());
			pst.setString(5, vo.getPhoto());
//			pst.setString(6, vo.getWdate());
			pst.setString(6, vo.getWriter());
			pst.setString(7, vo.getPwd());
			
			ResultSet rs = pst.executeQuery();
			System.out.println("입력완료");
			rs.next();
			pst.close();
//			conn.close();						
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		
	}
	public boolean thum(){
		boolean flag = false;
		try {
			String sql="update portfolio set thumb=photo where photo= ?";
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getPhoto());
			int cnt = pst.executeUpdate();
			flag = true;
			System.out.println("업데이트 완료");
			pst.close();
//			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return flag;
	}
	
	
	
	public void setVo2(PortfolioVo vo) {
		this.vo = vo;
		
		int size=1024*1024*10;
		String oriFile="";  //원본
		String sysFile="";  //저장될 파일명
		MultipartRequest multi=null;
		
		try
		{
			if(vo.getRequest() !=null){
			multi=new MultipartRequest
					(vo.getRequest(),saveDir,size,"utf-8",new DefaultFileRenamePolicy());
			Enumeration files = multi.getFileNames();
			String tempFile = (String)files.nextElement();
			
			oriFile = multi.getOriginalFileName(tempFile);
			sysFile = multi.getFilesystemName(tempFile);
			
			//vo.setRno(Integer.parseInt(multi.getParameter("rno")));
			vo.setCate(multi.getParameter("cate"));
			vo.setSubject(multi.getParameter("subject"));
			vo.setContent(multi.getParameter("content"));
			vo.setPhoto(sysFile);
			vo.setThumb(multi.getParameter("thumb"));
			vo.setWriter(multi.getParameter("writer"));
			vo.setPwd(multi.getParameter("pwd"));
			System.out.println("setvo2작업완료");
			}
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		  try {
	        	
	            //썸네일 가로사이즈
	            int thumbnail_width = 400;
	            //썸네일 세로사이즈
	            int thumbnail_height = 600;

	            	//원본이미지파일의 경로+파일명
	            	File origin_file_name = new File("F:/자바/학원/and_1406/2/kiSunnyShop/WebContent/memberPhoto/"+vo.getPhoto());
	            	File thumb_file_name = new File("F:/자바/학원/and_1406/2/kiSunnyShop/WebContent/thumb/"+vo.getPhoto());
	            
	            
//		            File origin_file_name = new File("D:/jsy/kiSunnyShop/WebContent/memberPhoto/"+vo.getPhoto());
//		            File thumb_file_name = new File("D:/jsy/kiSunnyShop/WebContent/thumb/"+vo.getPhoto());
		     
		            BufferedImage buffer_original_image = ImageIO.read(origin_file_name);
		            BufferedImage buffer_thumbnail_image = new BufferedImage(thumbnail_width, thumbnail_height, BufferedImage.TYPE_3BYTE_BGR);
		            Graphics2D graphic = buffer_thumbnail_image.createGraphics();
		            graphic.drawImage(buffer_original_image,0 , 0, thumbnail_width, thumbnail_height, null);
		            ImageIO.write(buffer_thumbnail_image, "jpg", thumb_file_name);
		        
		            System.out.println("썸네일 생성완료");
	        } catch (Exception e) {
	            e.printStackTrace();
	        }  
	}

	
	
	public boolean modify()
	{
		boolean flag = false;
		System.out.println(vo.getRno());
		String sql="update portfolio set cate=?, subject=?, content=?, photo=?, wdate=sysdate, writer=?, pwd=? where rno=?";
		try
		{
			
			PreparedStatement pst = conn.prepareStatement(sql);
			//pst.setString(1, "seq_portfolio_rno.nextval");
			pst.setString(1, vo.getCate());
			pst.setString(2, vo.getSubject());
			pst.setString(3, vo.getContent());
			pst.setString(4, vo.getPhoto());
			pst.setString(5, vo.getWriter());
			pst.setString(6, vo.getPwd());
			pst.setInt(7, vo.getRno());
			
			int cnt = pst.executeUpdate();
			flag = true;
			
			pst.close();
			conn.close();						
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		return flag;
	}

	public void page()    //페이지관련 연산 메서드
	{
		String sql="select count(*) cnt from portfolio where rno like ? ";
		try
		{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			//pst.setString(2, "%" + vo.getFind() + "%");
			ResultSet rs = pst.executeQuery();
			while(rs.next())
			{
			
				totSize = rs.getInt("cnt");
				
				//전체 페이지수
				totPage = (int)Math.ceil(totSize*1.0 / listSize);
				
				//전체 블럭수
				totBlock = (int)Math.ceil(totPage*1.0/ blockSize);
				
				//현재 블럭
				nowBlock = (int)Math.ceil(nowPage*1.0 / blockSize);
				
				System.out.println("리스트 사이"+listSize);
				//페이지의 시작과 끝번호
				endPage = nowBlock * blockSize;
				startPage = endPage - blockSize+1;
				
				//게시물의 시작번호와 끝 번호
				endNo = nowPage* listSize;
				startNo = endNo - listSize + 1;
				
				// endPage, endNo 보정
				if(endPage > totPage) endPage = totPage;
				if(endNo > totSize) endNo = totSize;
			
//			System.out.print("<li>nowBlock" + nowBlock+ "?");
//			System.out.println(listSize);
//			System.out.print("<li>totSize=" + totSize+ "?");
//			System.out.println("<li>totPage=" + totPage);
//			
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	
	public ArrayList<PortfolioVo> select()
	{
		conn = new MyOracle().getConn();
		page();
		al = new ArrayList<>();
		String sql=
				"select * from ("
				+ "select rownum rn, c.* from("
				+ " select * from portfolio "
				+ " where rno like ? or subject like ? order by rno desc )c"
				+ " ) where rn between ? and ?";
		try
		{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			pst.setString(2, "%" + vo.getFind() + "%");
			pst.setInt(3, startNo);
			pst.setInt(4, endNo);
			
			ResultSet rs = pst.executeQuery();
			while(rs.next())
			{
				
				PortfolioVo v = new PortfolioVo();
				v.setRno(rs.getInt("rno"));
				v.setPrno(rs.getInt("prno"));
				v.setCate(rs.getString("cate"));
				v.setSubject(rs.getString("subject"));
				v.setContent(rs.getString("content"));
				v.setPhoto(rs.getString("photo"));
				v.setThumb(rs.getString("thumb"));
				v.setWdate(rs.getString("wdate"));
				v.setWriter(rs.getString("writer"));
				v.setPwd(rs.getString("pwd"));
				v.setReview(rs.getInt("review"));
				al.add(v);
			}
			rs.close();
			pst.close();
			conn.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return al;
	}

	
	
	
	
	public ArrayList<PortfolioVo> select_top()
	{
		page();
		al = new ArrayList<PortfolioVo>();
		String sql=
				"select * from ("
				+ "select rownum rn, c.* from("
				+ " select * from portfolio "
				+ " where subject like ? order by rno desc )c"
				+ " ) where rn between ? and ?";

		try
		{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%"+ "coat"+ "%");
			pst.setInt(2, startNo);
			pst.setInt(3, endNo);
			
			
			ResultSet rs = pst.executeQuery();
			while(rs.next())
			{
				
				PortfolioVo v = new PortfolioVo();
				v.setRno(rs.getInt("rno"));
				v.setPrno(rs.getInt("prno"));
				v.setCate(rs.getString("cate"));
				v.setSubject(rs.getString("subject"));			
				v.setContent(rs.getString("content"));
				v.setPhoto(rs.getString("photo"));
				v.setWdate(rs.getString("wdate"));
				v.setWriter(rs.getString("writer"));
				v.setPwd(rs.getString("pwd"));
				v.setThumb(rs.getString("thumb"));
				
				al.add(v);
				
			}
			for(int i=0; i<al.size(); i++){				
				System.out.println("al의 데이터: "+al.get(i).getSubject());
			}
			rs.close();
			pst.close();
			conn.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return al;
	}
	
	public ArrayList<PortfolioVo> select_pants()
	{
		page();
		al = new ArrayList<PortfolioVo>();
		String sql=
				"select * from ("
				+ "select rownum rn, c.* from("
				+ " select * from portfolio "
				+ " where subject like ? order by rno desc )c"
				+ " ) where rn between ? and ?";

		try
		{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%"+ "pant"+ "%");
			pst.setInt(2, startNo);
			pst.setInt(3, endNo);
			
			
			ResultSet rs = pst.executeQuery();
			while(rs.next())
			{
				
				PortfolioVo v = new PortfolioVo();
				v.setRno(rs.getInt("rno"));
				v.setPrno(rs.getInt("prno"));
				v.setCate(rs.getString("cate"));
				v.setSubject(rs.getString("subject"));			
				v.setContent(rs.getString("content"));
				v.setPhoto(rs.getString("photo"));
				v.setWdate(rs.getString("wdate"));
				v.setWriter(rs.getString("writer"));
				v.setPwd(rs.getString("pwd"));
				v.setThumb(rs.getString("thumb"));
				al.add(v);
				
			}
			for(int i=0; i<al.size(); i++){				
				System.out.println("al의 데이터: "+al.get(i).getSubject());
			}
			rs.close();
			pst.close();
			conn.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return al;
	}
	
	public ArrayList<PortfolioVo> select_Shoes()
	{
		page();
		al = new ArrayList<PortfolioVo>();
		String sql=
				"select * from ("
				+ "select rownum rn, c.* from("
				+ " select * from portfolio "
				+ " where subject like ? order by rno desc )c"
				+ " ) where rn between ? and ?";

		try
		{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%"+ "shoes"+ "%");
			pst.setInt(2, startNo);
			pst.setInt(3, endNo);
			
			
			ResultSet rs = pst.executeQuery();
			while(rs.next())
			{
				
				PortfolioVo v = new PortfolioVo();
				v.setRno(rs.getInt("rno"));
				v.setPrno(rs.getInt("prno"));
				v.setCate(rs.getString("cate"));
				v.setSubject(rs.getString("subject"));			
				v.setContent(rs.getString("content"));
				v.setPhoto(rs.getString("photo"));
				v.setWdate(rs.getString("wdate"));
				v.setWriter(rs.getString("writer"));
				v.setPwd(rs.getString("pwd"));
				v.setThumb(rs.getString("thumb"));
				al.add(v);
				
			}
			for(int i=0; i<al.size(); i++){				
				System.out.println("al의 데이터: "+al.get(i).getSubject());
			}
			rs.close();
			pst.close();
			conn.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return al;
	}

	
	
	
	public PortfolioVo getVo() {
		return vo;
	}


	public void setVo(PortfolioVo vo) {
		this.vo = vo;
		
		this.nowPage = vo.getNowPage();
		this.nowBlock = vo.getNowBlock();
		int size=1024*1024*10;
		String oriFile="";  //원본
		String sysFile="";  //저장될 파일명
		MultipartRequest multi=null;
		
		try
		{
			if(vo.getRequest() !=null){
			multi=new MultipartRequest
					(
						vo.getRequest(),
						saveDir,
						size,
						"utf-8",
					new DefaultFileRenamePolicy()
					);
			Enumeration files = multi.getFileNames();
			String tempFile = (String)files.nextElement();
			
			oriFile = multi.getOriginalFileName(tempFile);
			sysFile = multi.getFilesystemName(tempFile);
			
			vo.setRno(Integer.parseInt(multi.getParameter("rno")));
			vo.setCate(multi.getParameter("cate"));
			vo.setSubject(multi.getParameter("subject"));
			vo.setContent(multi.getParameter("content"));
			vo.setPhoto(sysFile);
			vo.setWriter(multi.getParameter("writer"));
			vo.setPwd(multi.getParameter("pwd"));
			
			
		}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	

	
	
	public int getListSize() {
		return listSize;
	}


	public void setListSize(int listSize) {
		this.listSize = listSize;
	}


	public int getBlockSize() {
		return blockSize;
	}


	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}


	public int getTotSize() {
		return totSize;
	}


	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}


	public int getTotPage() {
		return totPage;
	}


	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}


	public int getTotBlock() {
		return totBlock;
	}


	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}


	public int getNowPage() {
		return nowPage;
	}


	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}


	public int getNowBlock() {
		return nowBlock;
	}


	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}


	public int getStartNo() {
		return startNo;
	}


	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}


	public int getEndNo() {
		return endNo;
	}


	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}


	public int getStartPage() {
		return startPage;
	}


	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}


	public int getEndPage() {
		return endPage;
	}


	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}

	public static void main(String [] args){
		new portDTO();
	}
	
}
